package de.ralbus.tfix_strk;

import java.util.Calendar;
import java.util.List;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.dropbox.sync.android.DbxAccountManager;
import com.dropbox.sync.android.DbxDatastore;
import com.dropbox.sync.android.DbxException;
import com.dropbox.sync.android.DbxTable;

public class DatastoreTaskActivity extends Activity {

	private static final String APP_KEY = "q7tdftla8clu1cq";
    private static final String APP_SECRET = "c18lbblbiw87pib";
    private static final String TAG = "DatastoreTaskActivity";
    private TextView textDatum;
    private static final int REQUEST_LINK_TO_DBX = 0;
    private DatePicker dpResult;
    private DbxAccountManager mDbxAcctMgr;
    private DbxDatastore mDatastore;
    
    private TaskTable mTaskTable;
    private int year;
	private int month;
	private int day;
	private String datum;
	
	private Button btmChangeDate;
	private Button btmSpeichern;

	static final int DATE_DIALOG_ID = 999;

    private DbxDatastore.SyncStatusListener mDatastoreListener = new DbxDatastore.SyncStatusListener() {
        @Override
        public void onDatastoreStatusChange(DbxDatastore ds) {
            Log.d(TAG, "SYNC STATUS: " + ds.getSyncStatus().toString());
            if (ds.getSyncStatus().hasIncoming) {
                try {
                    mDatastore.sync();
                } catch (DbxException e) {
                    handleException(e);
                }
            }
            updateList();
        }
    };
    
    void showToast(CharSequence msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();     //Einfach einen Toast erstellen
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDbxAcctMgr = DbxAccountManager.getInstance(getApplicationContext(), APP_KEY, APP_SECRET);
        setContentView(R.layout.activity_datastore_task);
        setCurrentDateOnView();
        
        Button linkButton = (Button) findViewById(R.id.link_button);
        linkButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mDbxAcctMgr.startLink((Activity)DatastoreTaskActivity.this, REQUEST_LINK_TO_DBX);
            }
        });

        Button newTaskButton = (Button) findViewById(R.id.new_task_button);
        newTaskButton.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                EditText nameInput = (EditText) findViewById(R.id.new_task_name);
                String taskName = nameInput.getText().toString();
                nameInput.setText("");
                findViewById(R.id.new_task_ui).setVisibility(View.GONE);
                try {
                    if (taskName.length() > 0) {
                    	
                        mTaskTable.createTask(taskName, datum);
                        
                    }
                } catch (DbxException e) {
                    handleException(e);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mDbxAcctMgr.hasLinkedAccount()) {
            // Ist ein Account verbunden
            showTasksView();
        } else {
            // Versteckt die Liste und zeigt den Link Button
            findViewById(R.id.link_button).setVisibility(View.VISIBLE);
            findViewById(R.id.new_task_ui).setVisibility(View.GONE);
            ((ViewGroup) findViewById(R.id.task_table)).removeAllViews();
        }
    }

    protected void onPause() {
        super.onPause();
        if (mDatastore != null) {
            mDatastore.removeSyncStatusListener(mDatastoreListener);
            mDatastore.close();
        }
    }


	@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_LINK_TO_DBX) {
            if (resultCode == RESULT_OK) {
                showTasksView();
            } else {
                // ... Link-Fehler oder vom User abgebrochen
                Toast.makeText(this, "Verbindung zur Dropbox fehlgeschlagen.", Toast.LENGTH_SHORT).show();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void showTasksView() {
        try {
            if (mDatastore == null||!mDatastore.isOpen()) {
                mDatastore = DbxDatastore.openDefault(mDbxAcctMgr.getLinkedAccount());
            }
            mTaskTable = new TaskTable(mDatastore);

            // Versteckt den Link Button und Zeigt die Liste
            findViewById(R.id.link_button).setVisibility(View.GONE);
//            findViewById(R.id.new_task_ui).setVisibility(View.VISIBLE);

            mDatastore.addSyncStatusListener(mDatastoreListener);
            mDatastore.sync();
            updateList();

            mDatastore.sync();
        } catch (DbxException e) {
            handleException(e);
        }

    }

    private void updateList() {
        List<TaskTable.Task> tasks;
        try {
            tasks = mTaskTable.getTasksSorted();
        } catch (DbxException e) {
            handleException(e);
            return;
        }

        TableLayout tableView = (TableLayout) findViewById(R.id.task_table);
        tableView.removeAllViews();

        for (final TaskTable.Task task: tasks) {
            TableRow row = (TableRow)getLayoutInflater().inflate(R.layout.task_row, null);
            TableRow row1 = (TableRow)getLayoutInflater().inflate(R.layout.task_row1, null);
            LinearLayout line = (LinearLayout) getLayoutInflater().inflate(R.layout.task_row2, null);            
            tableView.addView(row);
            tableView.addView(row1);
            tableView.addView(line);
            
            final TextView text = (TextView)row.findViewById(R.id.task_text);
            textDatum = (TextView)row1.findViewById(R.id.task_text_datum);
            textDatum.setText(task.getDatum());
            textDatum.setOnLongClickListener(new OnLongClickListener() {
	
				public boolean onLongClick(View v) {
				
					showDialog(DATE_DIALOG_ID);
					
					return false;
				}
			});
            
            Button delete = (Button)row.findViewById(R.id.delete_button);
            delete.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    try {
                        task.delete();
                    } catch (DbxException e) {
                        handleException(e);
                    }
                }
            });
            btmSpeichern = (Button)row1.findViewById(R.id.speichern_button);
            btmSpeichern.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
                	String tmp = textDatum.getText().toString();
                	try {
						task.setDatum(tmp);
					} catch (DbxException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                }
            });
            
            btmChangeDate = (Button)row1.findViewById(R.id.datum_button);
            btmChangeDate.setOnClickListener(new OnClickListener() {
                @SuppressWarnings("deprecation")
				public void onClick(View v) {
                	
                	showDialog(DATE_DIALOG_ID);
                	
                }
            });

            
//            CheckBox toggleComplete = (CheckBox)row.findViewById(R.id.completed_checkbox);
//            toggleComplete.setChecked(task.isCompleted());
//            toggleComplete.setOnClickListener(new OnClickListener() {
//                public void onClick(View v) {
//                    try {
//                        task.toggleCompleted();
//                    } catch (DbxException e) {
//                        handleException(e);
//                    }
//                }
//            });
            
            text.setText(task.getName());
            if (task.isCompleted()) {
                text.setPaintFlags(text.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            }
        }
    }

    private void handleException(DbxException e) {
        e.printStackTrace();
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
    
    //------------------------------Date Dialog------------------------------------------------------
    
    @Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			// Datum aus datepicker einsetzen
			return new DatePickerDialog(this, datePickerListener, year, month,
					day);
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// wenn die DialogBox geschlossen wird, wird onDateSet aufgerufen...
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;

			// .. und danach die Auswahl im Textview eingefuegt
			textDatum.setText(new StringBuilder().append(day)
					.append(".").append(month + 1).append(".").append(year)
					.append(" "));
			
			//Dann der Button versteckt
			btmChangeDate.setVisibility(View.GONE);
			btmSpeichern.setVisibility(View.VISIBLE);
			
			// den DatePicker initialisieren (voreinstellen)
			dpResult.init(year, month, day, null);

		}
	};
	
	// zeigt das aktuelle Datum
		public void setCurrentDateOnView() {

//			tvDisplayDate = (TextView) findViewById(R.id.tvDate);
			dpResult = (DatePicker) findViewById(R.id.dpResult);

			final Calendar c = Calendar.getInstance();
			year = c.get(Calendar.YEAR);
			month = c.get(Calendar.MONTH);
			day = c.get(Calendar.DAY_OF_MONTH);
			datum = (day+"."+(month + 1)+"."+year+" ");   //Kompettes Datum abspeichern
		
			// setzt das aktuelle Datum in das TextEdit
//			tvDisplayDate.setText(new StringBuilder()
//					// Month ist 0 basiert, immer plus 1
//					.append(day).append(".").append(month +1).append(".")
//					.append(year).append(" "));

			// aktuelles Datum in datepicker setzen
			dpResult.init(year, month, day, null);

		}
	
	//----------------------------------Menu------------------------------------------------------------
		
		@Override
		 public boolean onCreateOptionsMenu(Menu menu) {
			super.onCreateOptionsMenu(menu);
	    	MenuInflater inflater = getMenuInflater();
	    	inflater.inflate(R.menu.hauptmenu, menu);
	    	return true; 	
		    	
		    }
		
   	@Override
   	public boolean onOptionsItemSelected(MenuItem item){
   		super.onOptionsItemSelected(item); 
		    	int itemId = item.getItemId();
				if (itemId == R.id.opt_ueber) {
					findViewById(R.id.new_task_ui).setVisibility(View.VISIBLE);
			
//					AlertDialog.Builder builder = new AlertDialog.Builder(this);
//					builder.setMessage("Bitte Zugangsdaten in den Einstellungen eingeben");
//			        builder.setNeutralButton("Einstellungen", new DialogInterface.OnClickListener() {
//			        	//click Listener
//			        @Override
//					public void onClick(DialogInterface dialog, int item) {
//			        	showToast("Geht!");
//			           }
//
//			        });
//
//			        AlertDialog alert = builder.create();
//
//			        alert.show();        //zeige dialog
				} else if (itemId == R.id.opt_tfixBeenden) {
					System.exit(0);                //beenden
				}
		    	return true;   	
		    }
}
